package com.boot.core.handler;

import com.alibaba.fastjson.JSON;
import com.boot.common.constants.Code;
import com.boot.common.exception.CommonException;
import com.boot.common.message.AjaxResult;
import com.boot.common.utils.WebUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author Cheng JiYe
 * @description: 全局异常处理
 * @date 2020/10/3 22:41
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler
    @ResponseBody
    public AjaxResult allException(HttpServletRequest request, Exception e) {
        printRequestInfo(request);
        logger.error("出现错误：" + e.getMessage(), e);
        return new AjaxResult(Code.ErrorSystem.getCode(),Code.ErrorSystem.getMsg());
    }

    @ExceptionHandler(CommonException.class)
    @ResponseBody
    public AjaxResult commonException(HttpServletRequest request, CommonException e) {
        printRequestInfo(request);
        StackTraceElement[] stack = e.getStackTrace();
        StringBuffer errorLog = new StringBuffer("运行时错误：" + e.getMessage() + " -> ");
        for (StackTraceElement stackTraceElement : stack) {
            String msg = stackTraceElement.toString();
            if (msg.startsWith("com")) {
                errorLog.append(msg).append("\n");
                //break;
            }
        }
        logger.error(errorLog.toString());
        AjaxResult r = new AjaxResult();
        r.setCode(e.getCode());
        r.setMsg(e.getMsg());
        return r;
    }

    private void printRequestInfo(HttpServletRequest request) {
        String requestInfo = WebUtil.getCurrentUrl(request);
        logger.error("请求：" + requestInfo);
        Map<String, String> params = WebUtil.getRequestParams(request);
        if (params.size() > 0) {
            logger.error("[" + request.getMethod() + "] 参数：" + JSON.toJSONString(params));
        }
    }
}
